# -*- coding: utf-8 -*-
# created on 2017/02/28

from __future__ import division
from operator import itemgetter
from sympy import Union, Integer, FiniteSet
from mathsolver.functions.base import BaseEq, BaseFunction, BaseVariables, BaseSymbolValue
from mathsolver.functions.hanshu.helper import check_func, my_groupby
from mathsolver.functions.mathematica.mathematicaSolve import MathematicaSolve
from sympy import Symbol


class JiaoDianQiuCan(BaseFunction):
    """071.函数图像交点个数求参数"""
    def solver(self, *args):
        func1, func2, number = check_func(args[0]), check_func(args[1]), args[2].sympify()
        expr1, expr2 = func1.expression, func2.expression
        symbols = list((expr1 - expr2).free_symbols)
        variable = list(set(symbols).difference([Symbol("x"), Symbol("y")]))[0]
        math_solver = MathematicaSolve().solver(BaseEq([expr1, expr2]), BaseVariables(symbols)).output[0].value
        values = list(math_solver.keys())[0]  # 所有变量
        solutions = math_solver[values]
        index = values.index(variable)  # variable 变量的 index

        grouped = my_groupby(solutions, key=itemgetter(index))
        filtered_values = []
        for variable_value, solu in grouped.items():
            if len(solu) == number:
                # 如果是整数值，转换为 FiniteSet, 否则 Union 会报错
                if isinstance(variable_value, Integer):
                    variable_value = FiniteSet(variable_value)
                filtered_values.append(variable_value)
        res = Union(filtered_values)
        self.output.append(BaseSymbolValue({variable: res}))
        return self


if __name__ == '__main__':
    pass
